package net.bblot.lottery.webInterface;

import android.Manifest;
import android.app.DownloadManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.karics.library.zxing.android.CaptureActivity;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.game.UMGameAgent;

import net.bblot.lottery.PackegeConfig;
import net.bblot.lottery.activity.BaseDroidGapActivity;
import net.bblot.lottery.push.PushUtil;
import net.bblot.lottery.util.AppConfig;
import net.bblot.lottery.util.FileUtil;
import net.bblot.lottery.util.ImageUtils;
import net.bblot.lottery.util.Logger;
import net.bblot.lottery.util.NativeUtil;
import net.bblot.lottery.util.TextUtil;
import net.bblot.lottery.util.ToastUtill;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class WebInterface {
    public final static String TAG = "WebInterface";
    private BaseDroidGapActivity ca;

    public WebInterface(BaseDroidGapActivity ca) {
        this.ca = ca;
    }

    @JavascriptInterface
    public void hideSplashscreen() {
        if (ca != null) {
            ca.removeSplashScreen();
        }
    }


    /**
     * @param platform 将内容直接分享出去，platform:1 微信好友 2微信朋友圈 3qq好友 4 qq空间
     */
    @JavascriptInterface
    public void shareContent(int platform, String title, String content, String url, String
            imgurl, String pageId) {
//		Toast.makeText(ca, "imgurl"+imgurl , Toast.LENGTH_LONG).show();
//		addCustomerService("testurl",url);
        ca.share(platform, title, content, url, imgurl, pageId);
    }

    // @JavascriptInterface
    // public void registerPush(String account) {
    // XGPushManager.registerPush(ca.getApplicationContext(), account);
    // }
    //
    // @JavascriptInterface
    // public void unregisterPush() {
    // XGPushManager.unregisterPush(ca.getApplicationContext());
    // }

    @JavascriptInterface
    public void downLoadApk(String version, String downLoadUrl) {
        DownloadManager downloadManager = (DownloadManager) ca.getSystemService(Context
                .DOWNLOAD_SERVICE);
//        ToastUtill.showToast(ca,"url="+downLoadUrl+version+"version");
        Uri uri = Uri.parse(downLoadUrl);
        DownloadManager.Request request = new DownloadManager.Request(uri);

        String pre = "caipiao_" + AppConfig.getAppMetaData(ca.getApplicationContext(), "UMENG_CHANNEL");

        String downLoadPath = "";
        if (ca.getExternalCacheDir() != null) {
            downLoadPath = ca.getExternalCacheDir().getAbsolutePath() + File.separator + pre + version + ".apk";
        } else {
            downLoadPath = ca.getCacheDir().getAbsolutePath() + File.separator + pre + version + ".apk";
        }

        File file = new File(downLoadPath);
        if (file.exists()) {
            file.delete();
        }
        request.setVisibleInDownloadsUi(true);
        request.setDestinationUri(Uri.fromFile(file));
        long reference = downloadManager.enqueue(request);
        AppConfig.saveDownLoadReference(ca, version, reference, file.getAbsolutePath());
    }

    @JavascriptInterface
    public void scanQRCode(String type) {
        String[] str_permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission
                .RECORD_AUDIO};
        if (ContextCompat.checkSelfPermission(ca, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ca.setScanType(type);
            ActivityCompat.requestPermissions(ca, str_permissions, BaseDroidGapActivity.REQUEST_CODE_PERMISSION_QR_CODE);
        } else {
            Intent intent = new Intent(ca, CaptureActivity.class);
            intent.putExtra(CaptureActivity.KEY_TYPE, type);
            ca.startActivityForResult(intent, BaseDroidGapActivity.RequestCode_ScanQRCode);
        }

    }

    @JavascriptInterface
    public void getPushClientId() {
        String clientId = PushUtil.getClientId(ca);
//         Toast.makeText(ca, "getPushClientId()"+clientId ,
//         Toast.LENGTH_LONG).show();
        Logger.e(TAG, "getPushClientId=" + clientId);
        ca.noticePushClientId(clientId);
    }

    @JavascriptInterface
    public void getWifiState() {
        // Toast.makeText(ca, "getWifiState" , Toast.LENGTH_LONG).show();
        ca.noticeWifiStatusChange();
    }

    @JavascriptInterface
    public void scanWifi() {
        // Toast.makeText(ca, "scanWifi" , Toast.LENGTH_LONG).show();
        ca.serchWifi(true);
    }

    @JavascriptInterface
    public void onEventValue(String id, String json) {
        HashMap<String, String> map = new HashMap<String, String>();
        try {
            JSONObject jObject = new JSONObject(json);
            Iterator<String> iterator = jObject.keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                map.put(key, jObject.getString(key));
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        try {
            ca.onEventValue(id, map);
//			Toast.makeText(ca, "onEventValue" + id, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void getCamraImage(String type, String num) {
        ca.imageChoose(type, num);
    }

    @JavascriptInterface
    public void payWeixin(String appid, String token) {
//        try {
//            RequestMsg msg = new RequestMsg();
//            msg.setTokenId(token);
//            msg.setTradeType(MainApplication.WX_APP_TYPE);
//            msg.setAppId(appid);
//            PayPlugin.unifiedAppPay(ca, msg);
//        } catch (Exception e) {
//
//        }

    }

    @JavascriptInterface
    public void aliPay(String form, String hash) {
        Log.e(TAG, "hash:" + hash);
        Log.e(TAG, "form:" + form);
        Log.e(TAG, "当前线程:" + Thread.currentThread().getName());
        if (TextUtils.isEmpty(form)) {
            return;
        }
        final String finalForm = form;

        String historyUrl = null;
        if (!TextUtils.isEmpty(hash) && hash.startsWith("cptoback://")) {
            historyUrl = getIndexPath(hash.replace("cptoback://", ""));
        }
        final String finalHistoryUrl = historyUrl;
        ca.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(finalHistoryUrl)) {
                    ca.loadDataWithBaseURL(null, finalForm, "text/html", "utf-8", finalHistoryUrl);
                } else {
                    ca.loadDataWithBaseURL(null, finalForm, "text/html", "utf-8", null);
                }
            }
        });
    }




    @JavascriptInterface
    public void addCustomerService(String type, String num) {
        ClipboardManager cm = (ClipboardManager) ca.getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        cm.setPrimaryClip(ClipData.newPlainText(null, num));
        if (type.equals("qq")) {
            Toast.makeText(ca, "号码已复制到剪切板,正在为您打开qq", Toast.LENGTH_SHORT).show();
            String url1 = "mqqwpa://im/chat?chat_type=wpa&uin=" + num;
            Intent i1 = new Intent(Intent.ACTION_VIEW, Uri.parse(url1));
            i1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            i1.setAction(Intent.ACTION_VIEW);
            ca.startActivity(i1);
        } else if (type.equals("wx")) {
            Toast.makeText(ca, "微信号码已复制", Toast.LENGTH_SHORT).show();
//			Intent intent = new Intent();
//			ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui
// .LauncherUI");// 包名该有activity
//			intent.setAction(Intent.ACTION_MAIN);
//			intent.addCategory(Intent.CATEGORY_LAUNCHER);
//			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			intent.setComponent(cmp);
//			ca.startActivity(intent);
        } else if (type.equals("phone")) {
            Toast.makeText(ca, "号码已复制到剪切板,正在为您拨号", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + num);
            intent.setData(data);
            ca.startActivity(intent);
        } else {
            Toast.makeText(ca, "号码已复制到剪切板", Toast.LENGTH_SHORT).show();
        }
    }

    @JavascriptInterface
    public void saveScreenShot(String filename) {
        View view = ca.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        Bitmap bmp = view.getDrawingCache();
        try {
            ImageUtils.saveImageToSD(ca, PackegeConfig.CASH_DIR + filename, bmp, 90);
            ToastUtill.showToast(ca, "图片保存至" + PackegeConfig.CASH_DIR);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtill.showToast(ca, "图片保存失败");
        }
    }

    /**
     * 由于qq空间不支持纯图，所以加了后两个参数，其他分享传空即可
     */
    @JavascriptInterface
    public void shareScreenShot(int platform, String pageId, String title, String content) {
        View view = ca.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        Bitmap bmp = view.getDrawingCache();
        ca.shareImage(platform, bmp, pageId);
    }

    /**
     * 由于qq空间不支持纯图，所以加了后两个参数，其他分享传空即可
     */
    @JavascriptInterface
    public void shareScreenShot(int platform, String pageId) {
        View view = ca.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        Bitmap bmp = view.getDrawingCache();
        ca.shareImage(platform, bmp, pageId);
    }


    @JavascriptInterface
    public void openWebUrl(String url) {

        ca.loadUrl(url);
    }

    //bcy  获取代理商渠道编号，传递给js
    @JavascriptInterface
    public String getStationId() {
        String result = AppConfig.getAppMetaData(ca.getApplicationContext(), "STATION_ID");

//        if (result != null && !result.equals("") ) {
//            result = result.substring(1);    //截掉首位的英文字母。  如果配置为纯数字，没有办法传进来，不知道为什么
//        }
        return result;
    }

    //bcy  获取友盟渠道编号，传递给js
    @JavascriptInterface
    public String getUmengChannel() {
        String result = AppConfig.getAppMetaData(ca.getApplicationContext(), "UMENG_CHANNEL");
        return result;
    }

    /**
     * bcy 获取APP版本号,一般用不到
     *
     * @return
     */
    @JavascriptInterface
    public int getAppVersionCode() {

        Context ctx = ca.getApplicationContext();

        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    /**
     * bcy  获取APP版本名称（应用管理器上显示的app版本号）
     *
     * @return
     */
    @JavascriptInterface
    public String getAppVersionName() {
        String localVersion = "";
        Context ctx = ca.getApplicationContext();
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }


    /**
     * 获取第三方平台信息，用于第三方登录
     */
    @JavascriptInterface
    public void getPlatformInfo(String type, String platform, String id, String secret) {
        Logger.e(TAG, "getPlatformInfo");
        ca.getPlatformInfo(type, platform, id, secret);
    }

    @JavascriptInterface
    public void toast(String msg) {
        ToastUtill.showShortToast(this.ca, msg);
    }

    @JavascriptInterface
    public String getAesKey() {
        //return AppConfig.getAesKey(ca);
        return NativeUtil.getAesKey();
    }

    @JavascriptInterface
    public String getAesIv() {
        //return AppConfig.getAesIv(ca);
        return NativeUtil.getAesIv();
    }

    @JavascriptInterface
    public void copyTextToClipboard(String text) {
        if (TextUtil.copyTextToClipboard(text)) {
            Toast.makeText(ca, "已复制到剪切板", Toast.LENGTH_SHORT).show();
        }
    }

    @JavascriptInterface
    public void payStatistics(String money, String source) {
        if (!TextUtils.isEmpty(money)) {
            //设置场景类型
            try {
                MobclickAgent.setScenarioType(ca, MobclickAgent.EScenarioType.E_UM_GAME);
                UMGameAgent.pay(Double.valueOf(money), Double.valueOf(money), Integer.valueOf(source));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String getIndexPath(String hash) {
        String indexPage = "";
        List<File> list = FileUtil.searchFile(AppConfig.getWebRootDir(ca), PackegeConfig.INDEX_PAGE);
        if (list.size() > 0) {
            String path = list.get(0).getAbsolutePath();
            indexPage = "file:///" + path;
        } else {
            indexPage = "file:///android_asset/www/android.html";
        }
        if (!TextUtils.isEmpty(hash)) {
            indexPage += hash;
        }
        Logger.e(TAG, "indexpage:" + indexPage);
        return indexPage;

    }


}
